package wblog.web;

import cn.webwheel.Action;
import cn.webwheel.results.TemplateResult;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import wblog.domain.Article;
import wblog.domain.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class articles extends BaseAction {

    List<Article> articles;

    @Action
    public Object html() throws SQLException {
        itemCount = qr.query("select count(*) from Article", new ScalarHandler<Number>()).intValue();
        articles = qr.query("select * from Article join User on Article.authorId=User.id order by postDate desc limit ? offset ?",
                new ResultSetHandler<List<Article>>() {
                    @Override
                    public List<Article> handle(ResultSet rs) throws SQLException {
                        List<Article> list = new ArrayList<Article>();
                        while (rs.next()) {
                            Article article = new Article();
                            article.id = rs.getInt("id");
                            article.title = rs.getString("title");
                            article.content = rs.getString("content");
                            article.postDate = rs.getTimestamp("postDate");
                            article.tags = rs.getString("tags");
                            article.view = rs.getInt("view");
                            article.commentCount = rs.getInt("commentCount");
                            article.author = new User();
                            article.author.id = rs.getString("User.id");
                            article.author.name = rs.getString("User.name");
                            article.author.tags = rs.getString("User.tags");
                            list.add(article);
                        }
                        return list;
                    }
                }, pageSize, (pg - 1) * pageSize);
        return new TemplateResult(this);
    }

    public List<Article> getArticles() {
        return articles;
    }
}
